package demo.security;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

public class SecurityContextUtil {

	public static Authentication getAuthentication() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof AnonymousAuthenticationToken) {
			throw new AuthenticationServiceException("authentication not found");
		}
		
		return authentication;		
	}
	
	public static String getUsername() {		
		return getAuthentication().getName();
	}

	public static String getAccessToken() {
		
		OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) getAuthentication().getDetails();
	
		return	details.getTokenValue();
	}
}
